﻿using AutoMapper;
using B.S.DataBase.MyProject.Domain;
using B.S.DataBase.MyProject.ErrorCode;
using B.S.DataBase.MyProject.Infrastructure.Interface;
using B.S.DataBase.MyWrite.API.Appicant.Command;
using B.S.DataBase.MyWrite.API.Appicant.Command.Roles;
using MediatR;

namespace B.S.DataBase.MyWrite.API.Appicant.CommandHandler
{
    /// <summary>
    /// 角色添加命令处理
    /// </summary>
    public class AddRoleCommandHandler : IRequestHandler<AddRoleCommand, APIResult<Role>>
    {
        private readonly IBaseRepository<Role> roleRep;
        private readonly IMapper mapper;
        public AddRoleCommandHandler(IBaseRepository<Role> roleRep, IMapper mapper)
        {
            this.roleRep = roleRep;
            this.mapper = mapper;
        }

        /// <summary>
        /// 角色添加命令处理
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<APIResult<Role>> Handle(AddRoleCommand request, CancellationToken cancellationToken)
        {
            APIResult<Role> result = new APIResult<Role>();

            var model = mapper.Map<Role>(request);

            var list = roleRep.GetAll().FirstOrDefault(x => x.RoleName ==model.RoleName );

            if (list == null)
            {
                await roleRep.Add(model);
                result.data = model;

                result.Code = APIEnum.添加成功;
                result.Msg = APIEnum.添加成功.ToString();
            }
            else
            {
                result.data = model;
                result.Code = APIEnum.添加失败;
                result.Msg = APIEnum.添加失败.ToString();
            }


            return await Task.FromResult(result);
        }
    }
}
